<?php

namespace App\Http\Controllers\Guard\Car;

use App\Http\Controllers\Common\GuardController;
use App\Models\Car\CarInfo;
use App\Models\Car\FixCarOrder;
use App\Models\Car\Order;
use App\Models\Car\RentUnit;
use App\Models\Constant\CarConstant;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class FixCarOrderController extends GuardController {


    public function __construct() {
        $this->instance = new FixCarOrder();
    }

    //指派维修人员
    public function add(Request $request){

        $id = $request->input('order_id');
        $fix_imgs = $request->input('fix_imgs',[]);
        if(count($fix_imgs)>0){
            $fix_imgs = implode(',', $fix_imgs);
            $status = CarConstant::FIX_ORDER_END;
            FixCarOrder::query()->where('id',$id)->update(compact('fix_imgs','status'));

            //修改对应车状态
            $carOrder = FixCarOrder::query()->where('id',$id)->first();
            $car = CarInfo::query()->where('car_no',$carOrder->car_no)->first();
            if(empty($car))return responseFail('未找到对应的车辆！');
            $car->status = CarConstant::CAR_STATUS_FREE;
            $car->save();

        }else{
            $fix_people = $request->input('fix_people');
            $fix_factory = $request->input('fix_factory');
            if(!empty($fix_people)){
                $status = CarConstant::FIX_ORDER_WAIT_FIX;
                FixCarOrder::query()->where('id',$id)->update(compact('fix_people','fix_factory','status'));
            }
        }
        return responseSuccess();
    }

    public function lst(Request $request) {
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);
        $conditions = $request->input();
        $records = $this->instance->getLst($conditions)->with('getUser')
            ->paginate($pageSize,$this->getCol,'page',$page);
        foreach ($records as $record) {
            $record->first_img = Arr::first($record->imgs);
            $record->first_fix_img = Arr::first($record->fix_imgs);
        }
        return responseSuccess($records->items(),$records->total());
    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $record = $this->instance->getRecordById($id);
        $record->back_time = $record->back_time??date('Y-m-d H:i:s');
        return responseSuccess($record->toArray(),1);
    }

}
